package controller

import (
	"github.com/gin-gonic/gin"
	"go_code/gin-blog/dao/db"
	"go_code/gin-blog/model"
	"go_code/gin-blog/service"
	"log"
	"net/http"
	"strconv"
	"time"
)

func ArticleNew(c *gin.Context) {
	category, _ := db.GetAllCategoryList()
	//if err
	c.HTML(http.StatusOK, "views/post_article.html", category)
}
func AddArticle(c *gin.Context) {
	username := c.PostForm("author")
	title := c.PostForm("title")
	summary := c.PostForm("summary")
	//这里可能会错
	categoryId := c.PostForm("category_id")
	log.Printf("category_id=%v", categoryId)
	cateId, _ := strconv.ParseInt(categoryId, 10, 64)
	category, err := db.GetCategoryById(cateId)
	if err != nil {
		c.HTML(http.StatusInternalServerError, "views/500.html", nil)
	}
	content := c.PostForm("content")
	article := &model.ArticleDetail{
		ArticleInfo: model.ArticleInfo{
			CategoryId: cateId,
			Username:   username,
			Summary:    summary,
			Title:      title,
			CreateTime: time.Now(),
		},
		Content:  content,
		Category: *category,
	}

	flag, err := db.InsertArticleDetail(article)
	if !flag {
		c.HTML(http.StatusInternalServerError, "views/500.html", nil)
		return
	}
	//1.从service读取文章数据
	articleRecordList, err := service.GetArticleRecordList(0, 15)
	//for _,v := range articleRecordList{
	//	fmt.Println(v)
	//}
	if err != nil {
		c.HTML(http.StatusInternalServerError, "views/500.html", nil)
		return
	}
	//for k,v := range articleRecordList {
	//	fmt.Printf("articleRescordList[%v]=%v\n",k,v)
	//}
	//2.用于在页面显示所有的分类
	categoryList, err := service.GetAllCategoryList()
	if err != nil {
		c.HTML(http.StatusInternalServerError, "views/500.html", nil)
		return
	}
	//for k,v := range categoryList {
	//	fmt.Printf("categoryList[%v]=%v\n",k,v)
	//}
	c.HTML(http.StatusOK, "views/index.html", gin.H{
		"article_list":  articleRecordList,
		"category_list": categoryList,
	})

}
